from datetime import datetime

import orjson
from fastapi import APIRouter, Depends, HTTPException, Path, Body
from fastapi.responses import JSONResponse, Response
from sqlalchemy import select, func, desc, delete
from sqlglot.expressions import Array

from config.get_db import get_db_sync as get_db
from sqlalchemy.orm import Session, selectinload
from yg_crm import schemas, crud, orm
from utils.utility import result, RespResult, json_result_reps
from sqlalchemy.ext.asyncio import AsyncSession
from config.get_db import get_db as get_db_async


online_router = APIRouter()



@online_router.post("/config")
async def save_or_update_config(db: AsyncSession = Depends(get_db_async), params:dict=Body({})):
    conf = None
    if params.get('id'):
        conf = (
        (await db.execute(select(orm.SysCustomReportConfig).where(orm.SysJsonSettings.id == params.get('id')))).scalars().first()
        )
    if conf:
        conf.update_time = datetime.now()
        Id = conf.id
    else:
        conf = orm.SysCustomReportConfig(**params)
        conf.create_time = datetime.now()
        conf.create_by = conf.update_by
        db.add(conf)
        await db.flush() # 执行 insert,update,delete,同步新的id
        Id = conf.id
    await db.commit()
    return json_result_reps(data={"id": Id})


@online_router.post("/list")
async def config_list(db: AsyncSession = Depends(get_db_async), params: dict = Body(...)):
    data = {}
    al = select(orm.SysCustomReportConfig)
    count_query = select(func.count(orm.SysCustomReportConfig.id))
    # 汇总逻辑
    if params.get("type"):
        al = al.where(orm.SysCustomReportConfig.type == params.get("type"))
    if params.get("code"):
        al = al.where(orm.SysCustomReportConfig.code.like(f'%{params.get("code")}%'))
    if params.get("name"):
        al = al.where(orm.SysCustomReportConfig.name.like(f'%{params.get("name")}%'))

    if params.get("field"):
        orderExp = desc(getattr(orm.SysCustomReportConfig, params.get("field"))) \
            if params.get("order") == "descend" else getattr(orm.SysCustomReportConfig, params.get("field"))
    else:
        orderExp = orm.SysCustomReportConfig.id
    page = al.order_by(orderExp).limit(params.get("pageSize", 10)).offset(
        (params.get("current", 1) - 1) * params.get("pageSize", 10))
    rows = (await db.execute(page)).scalars().all()
    data['count'] = await db.scalar(count_query)
    data['rows'] = rows
    return json_result_reps(data=data)


@online_router.get("/detail/{item_id}")
async def detail_config(db: AsyncSession = Depends(get_db_async), item_id: int = Path(...), item_type: str = Path(...)):
    conf = None
    if item_id:
        conf = (
            (await db.execute(
                select(orm.SysCustomReportConfig)
                .options(selectinload(orm.SysCustomReportConfig.report_params))  # 预加载子表
                .where(orm.SysCustomReportConfig.id == item_id))).scalars().first()
        )
    await db.commit()
    return json_result_reps(data=conf)


@online_router.delete("/delete")
async def delete_config(db: AsyncSession = Depends(get_db_async), ids:list = Body(...)):
    print("delete....")
    # if isinstance(ids, int):
    #     ids = [ids]
    if ids:
        await db.execute(delete(orm.SysCustomReportConfig).where(orm.SysCustomReportConfig.id.in_(ids)))
        await db.commit()
    else:
        raise HTTPException(status_code=400, detail="删除失败，记录不存在！")
    return json_result_reps(message="删除成功", use_serializer=True)


